
package com.huaweicloud.haydn.delivercore.agent.service;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @since 2022-12-13
 */
@Service
@Slf4j
public class HttpRequestService {

    public <T> ResponseEntity<T> execute(String url, HttpMethod method, HttpEntity<?> entity, Class<T> responseType) {
        log.info("start http request, url: {}, method: {}", url, method);
        return registerTemplate().exchange(url, method, entity, responseType);
    }

    public RestTemplate registerTemplate() {
        RestTemplate restTemplate = new RestTemplate(getFactory());
        restTemplate.getMessageConverters().set(1, getConvert());
        return restTemplate;
    }

    private SimpleClientHttpRequestFactory getFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(6000);
        factory.setReadTimeout(600000);
        return factory;
    }

    private HttpMessageConverter getConvert() {
        StringHttpMessageConverter stringConvert = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        List<MediaType> stringMediaTypes = new ArrayList<>();
        stringMediaTypes.add(MediaType.TEXT_PLAIN);
        stringMediaTypes.add(MediaType.TEXT_HTML);
        stringMediaTypes.add(MediaType.APPLICATION_JSON);
        stringConvert.setSupportedMediaTypes(stringMediaTypes);
        return stringConvert;
    }
}
